<template>
  <view class="contain">
    <!-- banner部分 -->
    <view class="carousel-section">
      <u-swiper :list="topBanner"
                indicatorMode="dot"
                indicator
                indicatorStyle="bottom: 70rpx"
                height="450rpx"></u-swiper>
    </view>

    <!-- 主体内容 -->
    <view class="content">
      <!-- 标题和分享 -->
      <view class="header">
        <view class="header-inner">
          <view class="title-wrap">
            <text class="title">{{detail.ShopName}}</text>
          </view>
          <view class="tag-list">
            <text class="tag" v-for="(tag, index) in tagList" :key="index" v-if="index < 3">{{tag}}</text>
            <text class="tag more-tags" v-if="tagList.length > 3">+{{tagList.length - 3}}</text>
          </view>
          <view class="address-info">
            <view class="address-icon">
              <image src="https://wzws.wanshanlundiao.cn/upload/img/20250407/202504071011558093.png" mode="aspectFit"></image>
            </view>
            <view class="address-content">
              <text class="address-text">{{detail.Address || "暂无"}}</text>
              <text class="business-time">营业时间 {{detail.BusinessHours || "暂无"}}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作浮动按钮 -->
      <view class="float-btns">
        <view class="collect-btn" @click="toggleCollect">
          <image :src="isCollected ? 'https://wzws.wanshanlundiao.cn/upload/img/20250421/202504211126014296.png'
          : 'https://wzws.wanshanlundiao.cn/upload/img/20250421/202504211126014296.png'" mode="aspectFit"></image>
          <text>{{isCollected ? '已收藏' : '收藏'}}</text>
        </view>
        <view class="share-btn" @click="shareShop">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250407/202504071011497781.png" mode="aspectFit"></image>
          <text>分享</text>
          <button open-type="share" class="share-open-btn"></button>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-btns">
        <view class="btn navigation" @click="goPark">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250407/202504071011590925.png" mode="aspectFit"></image>
          <text>导航 (距离{{detail.Distance}})</text>
        </view>
        <view class="btn phone" @click="goPhone">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250407/202504071012035622.png" mode="aspectFit"></image>
          <text>拨打电话</text>
        </view>
      </view>
      
      <!-- 锚点导航 -->
      <view class="anchor-tabs">
        <view class="tab" :class="{active: activeAnchor === 'intro'}" @click="scrollToAnchor('intro')">
          <text>介绍</text>
        </view>
        <view class="tab" :class="{active: activeAnchor === 'packages'}" @click="scrollToAnchor('packages')" v-if="packageList.length > 0">
          <text>套餐</text>
        </view>
        <view class="tab" :class="{active: activeAnchor === 'products'}" @click="scrollToAnchor('products')">
          <text v-if="merchantsType === 2">门票</text>
          <text v-else-if="merchantsType === 3">产品</text>
          <text v-else-if="merchantsType === 4">房型</text>
          <text v-else-if="merchantsType === 5">服务</text>
          <text v-else-if="merchantsType === 6">摄影</text>
          <text v-else>商品</text>
        </view>
        <view class="tab" :class="{active: activeAnchor === 'reviews'}" @click="scrollToAnchor('reviews')">
          <text>评价({{reviewsTotal}})</text>
        </view>
      </view>

      <!-- 介绍部分 -->
      <view class="anchor-section" id="intro">
        <view class="section">
          <view class="section-title">
            <text>商家介绍</text>
          </view>
          <view class="intro-content">
            <view>{{detail.Introduction || '暂无商家介绍信息'}}</view>
          </view>
        </view>
      </view>

      <!-- 套餐部分 -->
      <view class="anchor-section" id="packages" v-if="packageList.length > 0">
        <view class="section">
          <view class="section-title">
            <text>套餐列表</text>
          </view>
          <view class="room-list">
            <Scenic v-for="(item, index) in packageList" :data="item" :key="index" @click="bookRoom(item.Id)"></Scenic>
          </view>
        </view>
      </view>

      <!-- 商品部分 -->
      <view class="anchor-section" id="products">
        <view class="section">
          <view class="section-title">
            <text v-if="merchantsType === 2">门票列表</text>
            <text v-else-if="merchantsType === 3">产品列表</text>
            <text v-else-if="merchantsType === 4">房型列表</text>
            <text v-else-if="merchantsType === 5">服务列表</text>
            <text v-else-if="merchantsType === 6">摄影服务</text>
            <text v-else>商品列表</text>
          </view>
          <view class="room-list" :class="{'gourmet-grid': merchantsType === 3}">
            <template v-if="merchantsType === 2">
              <Scenic v-for="(item, index) in foodList" :data="item" :key="index" @click="bookRoom(item.Id)"></Scenic>
            </template>
            <template v-if="merchantsType === 3">
              <Gourmet v-for="(item, index) in foodList" :data="item" :key="index" @click="bookRoom(item.Id)"></Gourmet>
            </template>
            <template v-if="merchantsType === 4">
              <Hotel v-for="(item, index) in foodList" :data="item" :key="index" @click="bookRoom(item.Id)"></Hotel>
            </template>
            <template v-if="merchantsType === 5">
              <Study v-for="(item, index) in foodList" :data="item" :key="index" @click="bookRoom(item.Id)"></Study>
            </template>
            <template v-if="merchantsType === 6">
              <Photography v-for="(item, index) in foodList" :data="item" :key="index" @click="bookRoom(item.Id)"></Photography>
            </template>
          </view>
        </view>
      </view>

      <!-- 评价部分 -->
      <view class="anchor-section" id="reviews">
        <view class="section">
          <view class="section-title">
            <text>用户评价({{reviewsTotal}})</text>
          </view>
          <view class="reviews-list">
            <!-- 评价项 -->
            <view class="review-item" v-for="(item, index) in reviewsList" :key="index">
              <view class="review-header">
                <view class="user-avatar">
                  <image :src="item.HeadImg || '/static/my/user.png'" mode="aspectFill"></image>
                </view>
                <view class="user-info">
                  <text class="user-name">{{item.UserName || '匿名用户'}}</text>
                  <text class="review-date">{{item.AddTime || ''}}</text>
                </view>
              </view>
              <view class="review-content">
                <text>{{item.Message || ''}}</text>
                <!-- 评价图片列表 -->
                <view class="review-images" v-if="item.ImgList && item.ImgList.split('|').length > 0">
                  <view class="image-list">
                    <image 
                      v-for="(img, imgIndex) in item.ImgList.split('|')" 
                      :key="imgIndex"
                      :src="img"
                      mode="aspectFill"
                      @click="previewImage(item.ImgList.split('|'), imgIndex)"
                    ></image>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 无评论时显示 -->
            <view class="no-reviews" v-if="reviewsList.length === 0">
              <text>暂无评论</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapMutations } from 'vuex'
import {getBusinessEvaluations, getGoodsList, getShopBgDetail} from '@/api/mall.js'
// 导入收藏相关API
import {getCheckCollection, getAddCollection, getCancelCollection} from '@/api/homePage.js'
import Hotel from "@/mall_subpages/merchants/detail/hotel.vue";
import Gourmet from "@/mall_subpages/merchants/detail/gourmet.vue";
import Scenic from "@/mall_subpages/merchants/detail/scenic.vue";
import Study from "@/mall_subpages/merchants/detail/study.vue";
import Photography from "@/mall_subpages/merchants/detail/photography.vue";

export default {
  name: "detail",
  components: {
    Photography,
    Study,
    Scenic,
    Gourmet,
    Hotel
  },
  data() {
    return {
      merchantsType: null,
      detail: {}, //商家详情
      shopID: 0, //商家ID
      topBanner: [], //顶部banner
      foodList: [], //产品数据
      packageList: [], //套餐数据
      goodsDetail: '',
      detailsText: "详情",
      activeAnchor: 'intro', // 当前活跃的锚点ID
      isCollected: false, // 是否已收藏
      reviewsList: [], // 评论列表数据
      reviewsTotal: 0, // 评论总数
      page: 1, // 当前评论页码
    }
  },
  computed: {
    tagList() {
      // 获取并限制标签数量
      const tags = this.detail.Tags ? this.detail.Tags.split(',').map(tag => tag.trim()) : [];
      return tags.filter(tag => tag); // 过滤掉空标签
    }
  },
  onLoad(options) {
    console.log(options)
    if (!options.id) {
      return
    }
    this.merchantsType = parseInt(options.type)
    this.shopID = options.id

    this.init();

    uni.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"]
    })
  },
  onPageScroll(e) {
    // 监听页面滚动更新激活的锚点
    this.updateActiveAnchor();
  },
  methods: {
    // 滚动到锚点
    scrollToAnchor(id) {
      this.activeAnchor = id;
      uni.createSelectorQuery()
        .select(`#${id}`)
        .boundingClientRect(rect => {
          if (rect) {
            uni.pageScrollTo({
              scrollTop: rect.top - 100, // 减去顶部导航的高度和一些间距
              duration: 300
            });
          }
        })
        .exec();
    },
    
    // 更新当前激活的锚点
    updateActiveAnchor() {
      uni.createSelectorQuery()
        .selectAll('.anchor-section')
        .boundingClientRect(rects => {
          if (rects && rects.length) {
            const scrollTop = uni.pageScrollTop || 0;
            const windowHeight = uni.getSystemInfoSync().windowHeight;
            const middleOfScreen = scrollTop + windowHeight / 3;
            
            // 找出在屏幕中间的锚点
            for (let i = 0; i < rects.length; i++) {
              const rect = rects[i];
              if (rect.top <= middleOfScreen && rect.bottom >= middleOfScreen) {
                this.activeAnchor = rect.id;
                break;
              }
            }
          }
        })
        .exec();
    },
    
    async init() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        const { Data } = await getShopBgDetail({
          Id: this.shopID
        })
        
        if (Data.LatitudeAndLongitude != null) {
          let JL = await this.GetDistance(Data.LatitudeAndLongitude.split(',')[0], 
                                         Data.LatitudeAndLongitude.split(',')[1]);
          if (JL < 1) {
            Data.Distance = JL * 1000 + 'M'
          } else {
            Data.Distance = JL + 'KM'
          }
        } else {
          Data.Distance = '未知'
        }
        this.detail = Data;
        if(Data.BusinesImgList){
          this.topBanner = Data.BusinesImgList?.split('|');
        }
        uni.setNavigationBarTitle({
          title: Data.ShopName
        })
        
        // 检查是否已收藏
        this.checkCollectionStatus();
        
        uni.hideLoading()
        this.getGoods();
        this.getEvaluation()
        
        // 页面加载完成后延迟执行一次锚点更新
        setTimeout(() => {
          this.updateActiveAnchor();
        }, 500);
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    },

    async getGoods() {
      try {
        const { Data } = await getGoodsList({
          BusinessId: this.shopID,
          Index: 1,
          Size: 100
        })
        uni.hideLoading();
        
        // 筛选套餐产品（Type=17的为套餐产品）
        this.packageList = Data.filter(item => item.Type === 17);
        // 筛选普通产品
        this.foodList = Data.filter(item => item.Type !== 17);
        
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    },

    async getEvaluation(){
      try {
        const res = await getBusinessEvaluations({
          Index: 1, // 使用固定的第一页，或使用this.page
          Size: 10,
        Id: this.shopID
        });
        
        if (res.Data) {
          this.reviewsList = res.Data; // 保存评论列表数据
          this.reviewsTotal = res.Total || 0; // 保存评论总数
        }
      } catch (error) {
        console.error('获取评论数据失败:', error);
        uni.showToast({
          title: '获取评论数据失败',
          icon: 'none'
        });
      }
    },
    //导航去
    goPark() {
      if (this.detail.LatitudeAndLongitude != null) {
        uni.openLocation({
          latitude: parseFloat(this.detail.LatitudeAndLongitude.split(',')[0]),
          longitude: parseFloat(this.detail.LatitudeAndLongitude.split(',')[1]),
          success: function() {
            console.log('打开系统位置地图成功')
          },
          fail: function(error) {
            console.log(error)
          }
        })
      }
    },
    //计算距离
    getSelfLocation() {
      let location = {
        lat: 0, //维度
        lng: 0, //经度
      }
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02', // 使用国标坐标系
          isHighAccuracy: true, // 高精度定位，会调用gps获取高精度坐标
          success(res) {
            location.lat = res.latitude
            location.lng = res.longitude,
            resolve(location);
          },
          fail(err) {
            reject(location);
          }
        })
      })
    },
    //进行经纬度转换为距离的计算
    Rad(d) {
      return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
    },
    //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
    async GetDistance(lat1, lng1) {
      uni.showLoading({});
      const res = await this.getSelfLocation()
      let lat2 = res.lat; //维度
      let lng2 = res.lng; //经度
      const radLat1 = this.Rad(lat1);
      const radLat2 = this.Rad(lat2);
      const a = radLat1 - radLat2;
      const b = this.Rad(lng1) - this.Rad(lng2);
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * 6378.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000; //输出为公里
      let newJL = s.toFixed(2);
      uni.hideLoading();
      return newJL;
    },
    // 预订房间
    bookRoom(goodsID) {
      uni.navigateTo({
        url: "/mall_subpages/goods/index?id=" + goodsID + "&type=" + this.merchantsType
      })
    },
    ...mapMutations(['setGoodsInfoList']),
    //拨打商家电话
    goPhone() {
      uni.makePhoneCall({
        phoneNumber: this.detail.Mobile
      });
    },
    // 检查收藏状态
    async checkCollectionStatus() {
      try {
        const res = await getCheckCollection({
          CollectionType: 1, // 商家收藏类型
          Id: this.shopID // 商家ID
        });
        
        if (res && res.Data) {
          this.isCollected = true;
        } else {
          this.isCollected = false;
        }
        console.log('收藏状态:', this.isCollected);
      } catch (error) {
        console.error('检查收藏状态失败:', error);
      }
    },
    
    // 切换收藏状态
    async toggleCollect() {
      try {
        if (this.isCollected) {
          // 取消收藏
          const res = await getCancelCollection({
            CollectionType: 1, // 商家收藏类型
            Id: this.shopID // 商家ID
          });
          this.isCollected = false;
          uni.showToast({
            title: '已取消收藏',
            icon: 'none',
            duration: 2000
          });
        } else {
          // 添加收藏
          const res = await getAddCollection({
            CollectionType: 1, // 商家收藏类型
            Id: this.shopID // 商家ID
          });
          this.isCollected = true;
          uni.showToast({
            title: '收藏成功',
            icon: 'success',
            duration: 2000
          });
        }
      } catch (error) {
        console.error('操作收藏失败:', error);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },
    // 分享
    shareShop() {
      console.log('分享商家');
      // 此方法是为了兼容点击事件，实际分享功能由open-type="share"处理
    },

    // 预览评价图片
    previewImage(urls, current) {
      uni.previewImage({
        urls: urls,
        current: current,
        indicator: 'number',
        loop: true
      });
    },
  },
}
</script>

<style lang="scss" scoped>
.contain{
  min-height: 100vh;
}
.content {
  margin-top: -40rpx;
  border-radius: 50rpx 50rpx 0 0;
  background-color: #F5F6F7;
  position: relative;
  z-index: 1;
  overflow: hidden;
  min-height: calc(100vh - 420rpx);
}

.header {
  display: flex;
  padding: 30rpx;
  background-color: #fff;

  .header-inner{
    flex: 1;
  }

  .title-wrap {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15rpx;

    .title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      flex: 1;
    }
  }
}

/* 标签列表样式 */
.tag-list {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15rpx;
  
  .tag {
    background-color: #F5F8FF;
    color: #498FFF;
    font-size: 22rpx;
    padding: 6rpx 15rpx;
    border-radius: 20rpx;
    margin-right: 15rpx;
    margin-bottom: 10rpx;
  }
  
  .more-tags {
    background-color: #F5F5F5;
    color: #999;
  }
}

/* 浮动操作按钮 */
.float-btns {
  position: absolute;
  top: 0;
  right: 30rpx;
  z-index: 10;
  display: flex;
  
  .share-btn,
  .collect-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100rpx;
    height: 100rpx;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    position: relative;
    
    image {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 6rpx;
    }
    
    text {
      font-size: 20rpx;
      color: #666;
    }
    
    .share-open-btn {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      z-index: 2;
      
      &::after {
        display: none;
      }
    }
  }
  
  .share-btn {
    background: #ffffff;
  }
  
  .collect-btn {
    background: #ffffff;
    
    &.active {
      text {
        color: #ff6633;
      }
    }
  }
}

.address-info {
  display: flex;
  padding: 15rpx 0;

  .address-icon {
    width: 21rpx;
    height: 25rpx;
    margin-right: 16rpx;
    display: flex;
    align-items: flex-start;
    padding-top: 6rpx;

    image {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .address-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10rpx;

    .address-text {
      font-size: 24rpx;
      color: #333;
    }

    .business-time {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.action-btns {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 30rpx 10rpx 30rpx;
  
  .btn {
    flex: 1;
    height: 80rpx;
    background: #fff;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6rpx;

    image {
      width: 28rpx;
      height: 28rpx;
      margin-right: 5rpx;
    }

    text {
      font-size: 24rpx;
      color: #333;
    }
  }
}

/* 锚点导航样式 */
.anchor-tabs {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 90rpx;
  background-color: #fff;
  margin-top: 20rpx;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.tab {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: relative;
  
  text {
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
  }
  
  &.active {
    text {
      font-weight: 600;
      color: #333;
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 6rpx;
      background-color: #00b7ff;
      border-radius: 3rpx;
    }
  }
}

/* 锚点内容样式 */
.anchor-section {
  margin-top: 20rpx;
  scroll-margin-top: 110rpx; /* 为锚点滚动留出空间 */
}

.section {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f2f2f2;
    
    text {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      position: relative;
    }
  }
  
  .room-list {
    padding: 20rpx;
    
    // 只有当类型为3(美食)时才使用网格布局
    &.gourmet-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-gap: 20rpx;
    }
  }
  
  .intro-content {
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 1.8;
  }
  
  .reviews-list {
    padding: 20rpx;
    
    .review-item {
      margin-bottom: 30rpx;
      
      .review-header {
        display: flex;
        align-items: center;
        margin-bottom: 15rpx;
        
        .user-avatar {
          width: 70rpx;
          height: 70rpx;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 15rpx;
          
          image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        
        .user-info {
          display: flex;
          flex-direction: column;
          
          .user-name {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
          }
          
          .review-date {
            font-size: 24rpx;
            color: #999;
            margin-top: 4rpx;
          }
        }
      }
      
      .review-content {
        padding-left: 85rpx;
        font-size: 28rpx;
        color: #333;
        line-height: 1.6;
        
        text {
          display: block;
          margin-bottom: 10rpx;
        }

        .review-images {
          margin-top: 15rpx;
          
          .image-list {
            display: flex;
            flex-wrap: wrap;
            gap: 10rpx;
            
            image {
              width: 160rpx;
              height: 160rpx;
              border-radius: 8rpx;
            }
          }
        }
      }
    }
  }
}
</style>